import pygame
from pygame.locals import *
from gordon.objects import SpriteSheet, Map, State
from gordon.core import StateMachine
from random import randint, seed

seed()

class Cow:
	def __init__(self, loc, area):
		self.loc = loc
		self.area = area
		
	def update(self):
		move_x = randint(-2,2) + self.loc[0]
		move_y = randint(-2,2) + self.loc[1]
		new_loc = (move_x, move_y)
		if new_loc[0] <= self.area[0] and new_loc[0] >=1:
			if new_loc[1] <= self.area[1] and new_loc[1] >=1:
					self.loc = new_loc
		
class Arena(State):
	def __init__(self, screen):
		State.__init__(self, 'Arena')
		self.screen = screen
		self.map = Map((40,30), 2)
		self.map_rect = (10,10, 640, 480)
		self.tile_shape = (16,16)
		self.cows = []
		self.cow_graphic = pygame.image.load('cow.png').convert()
		self.cow_graphic.set_colorkey((255,0,255))
		
	def update(self):
		for event in pygame.event.get():
			if event.type == pygame.QUIT: self.run
			elif event.type == KEYDOWN:
				if event.key == K_ESCAPE:
					self.run = False
				if event.key == K_q:
					self.run = False
				if event.key == K_a:
					self.cows.append(Cow((15,15),self.map.shape))
				if event.key == K_z:
					if len(self.cows) > 0:
						self.cows.pop()
					
	def draw(self):
		for y in range(self.map.shape[1]+1):
			for x in range(self.map.shape[0]+1):
				value = self.map.get_at((x,y))
				rect = (self.map_rect[0]+(x*self.tile_shape[0]), self.map_rect[1]+(y*self.tile_shape[1]), self.tile_shape[0], self.tile_shape[1])
				if value == None:
					screen.fill((0,240,0), rect)
		for c in self.cows:
			rect = (self.map_rect[0]+c.loc[0]*self.tile_shape[0], self.map_rect[0]+c.loc[1]*self.tile_shape[1],self.tile_shape[0],self.tile_shape[1])
			screen.blit(self.cow_graphic, rect)
			c.update()
					
		pygame.display.flip()

screen_size = (800,600)

pygame.init()
screen = pygame.display.set_mode(screen_size)
machine = StateMachine(_debug=True)

machine.push(Arena(screen))
#machine.push(EditLayer())
while 1:
	current = machine.top()
	if current.run:
		current.update()
		current.draw()
	else:
		machine.pop()
